package com.jzy.secondhandbooktradingmanagement.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;

import com.jzy.secondhandbooktradingmanagement.entity.User;
import com.jzy.secondhandbooktradingmanagement.mapper.UserMapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component
public class TokenUtils {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IRedisUtil redisUtil;

    private static UserMapper staticUserMapper;
    private static IRedisUtil staticRedisUtil;

    @PostConstruct
    public void init() {
        staticUserMapper = userMapper;
        staticRedisUtil = redisUtil;
    }

    /**
     * 生成token
     * @param user
     * @return
     */
    public static String genToken(User user) {
        return JWT.create().withExpiresAt(DateUtil.offsetDay(new Date(), 1)).withAudience(user.getId().toString())
                .sign(Algorithm.HMAC256(user.getPassword()));
    }

    /**
     * 获取token中的用户信息
     * @return
     */
    public static User getUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("authorization");
            if (token == null) {
                return null;
            }
            String aud = JWT.decode(token).getAudience().get(0);
            Integer userId = Integer.valueOf(aud);
            
            // 尝试从 Redis 获取用户信息
            String cacheKey = "user:id:" + userId;
            User cachedUser = staticRedisUtil.getValue(cacheKey);
            if (cachedUser != null) {
                return cachedUser;
            }

            // 缓存未命中，查询数据库
            User user = staticUserMapper.selectById(userId);
            if (user != null) {
                // 存入 Redis，设置过期时间，例如 30 分钟
                staticRedisUtil.setValue(cacheKey, user, 30 * 60 * 1000L);
            }
            return user;
        } catch (Exception e) {
            log.error("解析token失败", e);
            return null;
        }
    }
}
